package com.zpark.user_system.servlet;

import com.zpark.user_system.utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 删除用户数据
 */
@WebServlet("/user/delete_user.do")
public class DeleteUserServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取被删除用户的ID
        Integer id = Integer.parseInt(request.getParameter("id"));

        // 定义数据库连接对象信息
        Connection conn = null;
        PreparedStatement stat = null;

        try {
            // 获取数据库连接对象
            conn = JDBCUtils.getConnection();
            // 开启事务
            conn.setAutoCommit(false);
            // 编写sql
            String sql = "delete from user where id = ?";
            // 获取预编译对象
            stat = conn.prepareStatement(sql);
            // 替换占位符
            stat.setInt(1, id);
            // 执行sql
            stat.executeUpdate();

            // 提交事务
            conn.commit();

            // 删除完成之后返回查看用户列表页面
            request.getRequestDispatcher("/user/find_user_all.do").forward(request, response);
        } catch(Exception e) {
            // 事务回滚
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            // 关闭数据库连接
            JDBCUtils.close(conn, stat, null);
        }
    }
}
